package com.bwei.like.mynewstop.base;

import android.text.TextUtils;

import com.bwei.like.mynewstop.app.MyApplication;
import com.bwei.like.mynewstop.utils.CommonUtils;
import com.bwei.like.mynewstop.utils.MD5Encoder;
import com.bwei.like.mynewstop.utils.NetUtils;
import com.nostra13.universalimageloader.utils.L;

import org.xutils.common.Callback;
import org.xutils.common.util.LogUtil;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

/**
 * Created by LiKe on 2016/10/31.
 */
public abstract class BaseData {
    /**
     * 网络出错
     */
    public static final int Error_Net = 100;
    /**
     * 请求出错
     */
    public static final int Error_Result = 200;

    /**
     * 时间值
     * @param path
     * @param time
     */
    public static final  long LONGTTIME=1000*60*60*72;
    public static final  long SHORTTIME=1000*60*10;
    public static final  long NOTIME=0;
    public void getData(String path, long time) {

        LogUtil.i("+++网络下载"+path);

        if (time == 0){
            getDataFromNet(path,time);
        }else {
            //首先判断本地是否有数据
            String data = getDataFromLocal(path, time);
            if (TextUtils.isEmpty(data)) {
                //请求网络
                getDataFromNet(path, time);
            } else {
                //证明有数据
                setResultData(data);
            }
        }

    }

    public abstract void setResultData(String path);

    //请求网络
    private void getDataFromNet(final String path, final long time) {
        //首先判断网络状态
        int netWorkType = NetUtils.getNetWorkType(MyApplication.getContext());
        //证明有网络
        if (netWorkType != NetUtils.NETWORKTYPE_INVALID) {
            RequestParams requestParams = new RequestParams(path);

            x.http().get(requestParams, new Callback.CommonCallback<String>() {
                @Override
                public void onSuccess(final String json) {
                    setResultData(json);
                    //通过线程将数据写入本地
                    CommonUtils.executeRunnable(new Runnable() {
                        @Override
                        public void run() {
                            //将数据写入本地
                            writeDataToLocal(json, path, time);
                        }
                    });
                }

                @Override
                public void onError(Throwable throwable, boolean b) {
                    //请求出错
                    setFailResult(Error_Result);
                }

                @Override
                public void onCancelled(CancelledException e) {

                }

                @Override
                public void onFinished() {

                }
            });
        } else {
            //网络出现问题
            setFailResult(Error_Net);
        }

    }

    protected abstract void setFailResult(int error_Net);

    private void writeDataToLocal(String json, String path, long time) {
        //获取缓存路径
        File cacheDir = MyApplication.getContext().getCacheDir();
        File file = null;
        try {
            file = new File(cacheDir, MD5Encoder.encode(path));
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (!file.exists()){
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        BufferedWriter bufferedWriter = null;
        //将数据写入
        try {
            bufferedWriter = new BufferedWriter(new FileWriter(file.getAbsolutePath()));
            //先写入时间
            bufferedWriter.write(System.currentTimeMillis()+ "\r\n");
            //在将字符串写入
            bufferedWriter.write(json);
            bufferedWriter.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (bufferedWriter != null) {
                    bufferedWriter.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    //读取数据
    private String getDataFromLocal(String path, long time) {
        File cacheDir = MyApplication.getContext().getCacheDir();
        File file = null;
        try {
            file = new File(cacheDir, MD5Encoder.encode(path));
        } catch (Exception e) {
            e.printStackTrace();
        }
        BufferedReader bufferedReader = null;
        try {
            bufferedReader = new BufferedReader(new FileReader(file.getAbsolutePath()));

            //读取第一行时间判断是否在有效时间内
            long t = Long.parseLong(bufferedReader.readLine());
            //判断当前时间如果时间差大于有效时间，说明已经过期，接着读取json串
            if (System.currentTimeMillis() - t < time) {
                StringBuilder builder = new StringBuilder();
                String line = null;
                while ((line = bufferedReader.readLine()) != null) {
                    builder.append(line);
                }
                //将读取完的json串返回
                return builder.toString();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (bufferedReader!=null)
                    bufferedReader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }


}
